package ssm.controller;

import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import ssm.domain.Role;
import ssm.domain.UserInfo;
import ssm.service.IUserService;

import java.util.List;

/*主要完成对用户信息的相关处理：如查询所有用户信息等*/
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @RequestMapping("/addRoleToUser.do")
    /*此处完成根据查询到的角色id，将其和用户的id进行绑定*/
    public String addRoleToUser(@RequestParam(name = "userId",required = true) String userId, @RequestParam(name = "ids",required = true)String[] roleIds){
        userService.addRoleToUser(userId,roleIds);

        return "redirect:findAll.do";

    }

    @RequestMapping("/findUserByIdAndAllRole.do")
    /*实现根据用户的id查询到该用户的信息，及还可以添加的角色信息*/
    public ModelAndView findUserByIdAndAllRole(@RequestParam(name = "id",required = true) String userId) throws Exception {
        ModelAndView mv = new ModelAndView();

        UserInfo userInfo = userService.findById(userId);
        List<Role> otherRoles = userService.findOtherRoles(userId);

        mv.addObject("user",userInfo);
        mv.addObject("roleList",otherRoles);
        mv.setViewName("user-role-add");

        return mv;
    }

    @RequestMapping("/findById.do")
    public ModelAndView findById(String id) throws Exception {
       UserInfo userInfo =  userService.findById(id);

        ModelAndView mv = new ModelAndView();
        mv.addObject("user",userInfo);
        mv.setViewName("user-show1");

        return mv;
    }

    @RequestMapping("/save.do")
    public  String  save(UserInfo userInfo) throws Exception {
        userService.save(userInfo);

        /*此处需要重新查询相关信息。即可以直接跳转到上次的查询所有页面*/
        return "redirect:findAll.do";
    }


    @RequestMapping("/findAll.do")
    public ModelAndView findAll() throws Exception {
        ModelAndView mv = new ModelAndView();

        List<UserInfo> userList =  userService.findAll();

//        此处只有用pageHelper中的pageInfo处理成该对象后，才才能方便获取其中的总条数，总页数等信息
        PageInfo pageInfo = new PageInfo(userList);
        mv.addObject("pageInfo",pageInfo);
        mv.setViewName("user-list");

        return mv;
    }

}
